/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.edu.nus.iss.pacman.manager.webservice;

import java.util.Vector;
import sg.edu.nus.iss.pacman.dao.Maze;
import sg.edu.nus.iss.pacman.dao.UserProfile;
import sg.edu.nus.iss.pacman.manager.dao.MazeManager;
import sg.edu.nus.iss.pacman.midlet.PacManScreen;
import sg.edu.nus.iss.pacman.net.webservice.WebServiceClient;
import sg.edu.nus.iss.pacman.net.webservice.WebServiceClientListener;

/**
 * A WebService manager class.
 * @author fredy
 */
public class WebServiceClientManager implements WebServiceClientListener
{
    private PacManScreen screen;
    private WebServiceClient client;

    /**
     * Creates a new instance of WebServiceClientManager.
     * @param serverURL the server URL
     * @param screen the screen
     */
    public WebServiceClientManager(String serverURL, PacManScreen screen)
    {
        this.screen = screen;
        client = new WebServiceClient(serverURL, this);
    }

    /**
     * Uploads the user profile.
     * @param userProfile the user profile
     */
    public void uploadUserProfile(UserProfile userProfile)
    {
        client.addUserProfile(userProfile);
    }

    /**
     * Retrieves the map listing.
     */
    public void retrieveMapListing()
    {
        client.retrieveMapListing();
    }

    public void userProfileUploaded()
    {
        screen.displayInfo("User profile has been successfully uploaded to the server");
    }

    public void mapListingRetrieved(String[] maps)
    {
        if (maps == null)
        {
            screen.displayInfo("Error connecting to the server");
        }
        else
        {
            String[] filteredMaps=getFilteredMazeList(maps);
            if(filteredMaps.length>0)
            {
                screen.displayDownloadedMazeList(getFilteredMazeList(maps));
            }else
            {
                screen.displayInfo("No new maps are available.\nPlease check later");

            }
        }
    }

    private String[] getFilteredMazeList(String[] maps)
    {
        MazeManager manager = new MazeManager();
        Vector mazeVector = new Vector();
        for (int i = 0; i < maps.length; i++)
        {
            Maze foundMaze = manager.findMaze(maps[i]);
            if (foundMaze == null)
            {
                mazeVector.addElement(maps[i]);
            }
        }
        String[] mazeArray = new String[mazeVector.size()];
        mazeVector.copyInto(mazeArray);
        return mazeArray;
    }
}
